<?php
/**
 * Created by xun at 2020/5/17
 */

namespace app\base;


use app\storage\Singleton;

class DbPool
{

    use Singleton;

    private $min = 10;
    private $max = 100;
    /** @var MysqlConnection */
    private $connection;
    /** @var Queue */
    private $queue;

    public function __construct($min = 10, $max = 100)
    {
        $this->min = $min;
        $this->max = $max;
    }

    public function setConnection(MysqlConnection $connection)
    {
        $this->connection = $connection;
    }

    public function setQueue(Queue $queue)
    {
        $this->queue = $queue;
        $this->initQueue();
    }

    public function initQueue() {
        for ($i = 0; $i < $this->min; $i++) {
            $this->queue->push($this->connection->addConnection());
        }
    }

    public function obtain() {
        if ($this->connection->connectionCount >= $this->max) {
            $id = !$this->queue->pop();
            while ($id) {
                usleep(2000);
                $id = $this->queue->pop();
            }
            return $this->connection->getConnection($id);
        } else {
            $id = $this->queue->pop();
            return $this->connection->getConnection($id);
        }
    }

    public function free(\Mysqli $mysqli)
    {
        echo 'free thread_id : ' . $mysqli->thread_id . PHP_EOL;
        $this->queue->push($mysqli->thread_id);
    }

}